package com.gxa.realm;

import com.gxa.entity.User;
import com.gxa.mapper.UserMapper1;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description:
 * @Author: zhuiyi
 * @CreatTime: 2022/9/26 12:46
 **/
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserMapper1 userMapper1;
//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("--------------->UserRealm--认证方法-------------");

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        User user = userMapper1.queryByUserName(((UsernamePasswordToken) token).getUsername());

        ByteSource salt = ByteSource.Util.bytes(user.getSalt());//加盐加密
        AuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPwd(),salt,this.getName());
        return info;

    }
//授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("--------------->UserRealm--授权方法-------------");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> perms = new HashSet<>();
        User user = (User) principalCollection.getPrimaryPrincipal();
        System.out.println(user);
        if("admin".equals(user.getUserName())){
            perms.add("emp:list");
            perms.add("emp:add");
            perms.add("emp:update");
            perms.add("emp:delete");
        }else if("zs".equals(user.getUserName())){
            perms.add("emp:list");
            perms.add("emp:add");
            perms.add("emp:update");
        }else if("ls".equals(user.getUserName())){
            perms.add("emp:list");
        }

        info.addStringPermissions(perms);
        System.out.println(perms);
        return info;
    }


}
